// 导入所需的 Angular 核心模块和功能模块
import { Component, OnInit, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatTableModule, MatTable } from '@angular/material/table';
import { MatPaginatorModule, MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { ColumnConfig, ColumnConfigDialogComponent } from '../column-config-dialog/column-config-dialog.component';

import { DormitoryService } from '../../services/dormitory.service';
import { Dormitory, DormitoryQuery } from '../../types/dormitory';
import { DormitoryFormComponent } from '../dormitory-form/dormitory-form.component';
import { ConfirmDialogComponent } from '../confirm-dialog/confirm-dialog.component';
import { LoadingDirective } from '../../directives/loading.directive';

@Component({
  selector: 'app-dormitory-list',
  standalone: true, // 声明为独立组件
  imports: [
    // 导入所需的 Angular Material 组件和其他模块
    CommonModule,
    FormsModule,
    MatTableModule,
    MatPaginatorModule,
    MatInputModule,
    MatFormFieldModule,
    MatButtonModule,
    MatIconModule,
    MatDialogModule,
    MatSnackBarModule,
    MatProgressSpinnerModule,
    LoadingDirective
  ],
  templateUrl: './dormitory-list.component.html',
  styleUrl: './dormitory-list.component.scss'
})
export class DormitoryListComponent implements OnInit {
  // 表格显示的列
  displayedColumns: string[] = [];
  
  // 列配置数组，定义表格的列信息
  columnConfigs: ColumnConfig[] = [
    { key: 'room_number', title: '房间号', visible: true },
    { key: 'building', title: '楼栋', visible: true },
    { key: 'floor', title: '楼层', visible: true },
    { key: 'capacity', title: '容量', visible: true },
    { key: 'occupied', title: '已住人数', visible: true },
    { key: 'status', title: '状态', visible: true },
    { key: 'description', title: '描述', visible: true },
    { key: 'actions', title: '操作', visible: true }
  ];

  // 表格数据源
  dataSource: Dormitory[] = [];
  // 总记录数
  total = 0;
  // 每页显示的记录数
  pageSize = 10;
  // 当前页码（从0开始）
  pageIndex = 0;
  // 楼栋筛选条件
  buildingFilter = '';

  // 获取分页器实例的引用
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  // 获取表格实例的引用
  @ViewChild(MatTable) table!: MatTable<Dormitory>;

  // 注入所需的服务
  constructor(
    private dormitoryService: DormitoryService, // 宿舍数据服务
    private dialog: MatDialog,                   // 对话框服务
    private snackBar: MatSnackBar               // 提示消息服务
  ) {}

  // 组件初始化时执行
  ngOnInit(): void {
    this.loadColumnConfigs(); // 加载列配置
    this.loadDormitories();   // 加载宿舍数据
  }

  // 从 localStorage 加载列配置
  private loadColumnConfigs(): void {
    const savedConfigs = localStorage.getItem('dormitoryListColumns');
    if (savedConfigs) {
      const configs = JSON.parse(savedConfigs);
      // 合并保存的配置和默认配置
      this.columnConfigs = this.columnConfigs.map(col => ({
        ...col,
        visible: configs.find((c: ColumnConfig) => c.key === col.key)?.visible ?? col.visible
      }));
    }
    this.updateDisplayedColumns();
  }

  // 更新显示的列
  private updateDisplayedColumns(): void {
    // 过滤出可见的列并获取其键值
    this.displayedColumns = this.columnConfigs
      .filter(col => col.visible)
      .map(col => col.key);
  }

  // 打开列配置对话框
  openColumnConfig(): void {
    const dialogRef = this.dialog.open(ColumnConfigDialogComponent, {
      data: { columns: this.columnConfigs }
    });

    // 处理对话框关闭后的结果
    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.columnConfigs = result;
        // 保存配置到 localStorage
        localStorage.setItem('dormitoryListColumns', JSON.stringify(result));
        this.updateDisplayedColumns();
      }
    });
  }

  // 加载状态标志
  isLoading = false;

  // 加载宿舍数据
  loadDormitories(): void {
    this.isLoading = true;
    // 构建查询参数
    const query: DormitoryQuery = {
      page: this.pageIndex + 1,
      page_size: this.pageSize,
      building: this.buildingFilter || undefined
    };

    // 调用服务获取数据
    this.dormitoryService.getDormitories(query).subscribe({
      next: (response) => {
        this.dataSource = response.data.dormitories;
        this.total = response.data.total;
        this.table.renderRows(); // 刷新表格行
        this.isLoading = false;
      },
      error: (error) => {
        this.snackBar.open('加载宿舍列表失败', '关闭', { duration: 3000 });
        console.error('Error loading dormitories:', error);
        this.isLoading = false;
      }
    });
  }

  // 处理分页事件
  onPageChange(event: PageEvent): void {
    this.pageIndex = event.pageIndex;
    this.pageSize = event.pageSize;
    this.loadDormitories();
  }

  // 应用筛选条件
  applyFilter(): void {
    this.pageIndex = 0; // 重置到第一页
    if (this.paginator) {
      this.paginator.firstPage();
    }
    this.loadDormitories();
  }

  // 打开宿舍表单对话框（新增/编辑）
  openDialog(dormitory?: Dormitory): void {
    const dialogRef = this.dialog.open(DormitoryFormComponent, {
      width: '500px',
      data: dormitory // 传入宿舍数据（编辑时）
    });

    // 处理对话框关闭后的结果
    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        if (result.id) {
          // 更新现有宿舍
          this.dormitoryService.updateDormitory(result.id, result).subscribe({
            next: () => {
              this.snackBar.open('宿舍信息更新成功', '关闭', { duration: 3000 });
              this.loadDormitories();
            },
            error: (error) => {
              this.snackBar.open('宿舍信息更新失败', '关闭', { duration: 3000 });
              console.error('Error updating dormitory:', error);
            }
          });
        } else {
          // 创建新宿舍
          this.dormitoryService.createDormitory(result).subscribe({
            next: () => {
              this.snackBar.open('宿舍创建成功', '关闭', { duration: 3000 });
              this.loadDormitories();
            },
            error: (error) => {
              this.snackBar.open('宿舍创建失败', '关闭', { duration: 3000 });
              console.error('Error creating dormitory:', error);
            }
          });
        }
      }
    });
  }

  // 删除宿舍
  deleteDormitory(id: number): void {
    // 打开确认对话框
    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      width: '400px',
      data: {
        title: '确认删除',
        message: '确定要删除这个宿舍吗？此操作不可撤销。'
      }
    });

    // 处理确认对话框的结果
    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        // 用户确认删除
        this.dormitoryService.deleteDormitory(id).subscribe({
          next: () => {
            this.snackBar.open('宿舍删除成功', '关闭', { duration: 3000 });
            this.loadDormitories(); // 重新加载数据
          },
          error: (error) => {
            this.snackBar.open('宿舍删除失败', '关闭', { duration: 3000 });
            console.error('Error deleting dormitory:', error);
          }
        });
      }
    });
  }
}